import React, {useState, useRef, useEffect} from 'react'
import {message, Button, Tabs, Divider,Popconfirm} from 'antd'
import {PageHeaderWrapper} from '@ant-design/pro-layout'
import ProTable, {ProColumns} from '@ant-design/pro-table'
import {connect} from 'umi'
import {queryAwardList, saveAwardInfo, awardBpm,getReAndPu} from '../service'
import { awardStatusList, BPMStatusEnum } from '@/utils/constant'
import {formatNumber} from '@/utils/utils'
import CreateForm from './components/CreateForm'
import moment from 'moment'

const {TabPane} = Tabs;

const TableList = () => {
  const actionRef = useRef();
  const actionRef2 = useRef();
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [tabIndex, setTabIndex] = useState("1");
  const [show, setShow] = useState(false);
  const [reanpu,setReanpu] = useState([]);
  const [record, setRecord] = useState(null);

  useEffect(()=>{
    getReAndPu().then((res)=>{
      setReanpu(res);
    })
  }, []);

  const updateAward = (record) => {
    setVisible(true);
    setRecord(record);
  };

  const detailsAward = (record) => {
    setVisible(true);
    setRecord(record);
    setShow(true);
  };

  const addAward = () => {
    setVisible(true);
  };

  const handleCancel = () => {
    setVisible(false);
    setRecord(null);
    setShow(false);
  };


  const handleSubmit = (values) => {
    setLoading(true);
    saveAwardInfo(values).then((res) => {
      if (res.flag) {
        handleCancel();
        message.success('奖罚操作成功！');
        actionRef.current.reload();
      } else {
        message.error(res.error);
      }
      setLoading(false);
    })
  };

  const sendAwardBpm = (id) => {
    awardBpm(id).then(res => {
      if (res.flag) {
        message.success('bpm发起成功！');
        actionRef.current.reload();
        window.open(res.data);
      } else {
        message.error(`bpm错误:` + res.error);
      }
    });
  };

  const handleChangTabIndex = (key) => {
    setTabIndex(key);
    if (key === '1') {
      actionRef.current && actionRef.current.reload();
    } else {
      actionRef2.current && actionRef2.current.reload();
    }
  };

  const columns = [
    {
      title: '流水号',
      dataIndex: 'serialNum',
      key: 'serialNum',
      hideInSearch: true
    },
    {
      title: '申请人',
      dataIndex: 'applicantName',
      key: 'applicantName',
    },
    {
      title: '申请人工号',
      dataIndex: 'usercode',
      key: 'usercode',
    },
    {
      title: '分配金额',
      dataIndex: 'distributionAmount',
      hideInSearch: true,
      render: (text) => {
        return formatNumber(text)
      },
    },
    {
      title: '奖罚名称',
      dataIndex: 'awardName',
    },
    {
      title: '奖罚公司',
      dataIndex: 'orgname',
    },
    {
      title: '奖罚种类',
      dataIndex: 'type',
      hideInSearch: true,
      render: (text) => {
        const res = reanpu.find((item) => item.id == text);
        return res ? res.name : text;
      }
    },
    {
      title: '开始日期',
      hideInTable: true,
      dataIndex: 'startTime',
      valueType: 'date',
    },
    {
      title: '结束日期',
      hideInTable: true,
      dataIndex: 'endTime',
      valueType: 'date',
    },
    {
      title: '申请日期',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (text) => {
        return text != '-' ? moment(text).format('YYYY-MM-DD') : '';
      },
    },
    {
      title: '审批状态',
      dataIndex: 'approvalStatus',
      key: 'approvalStatus',
      hideInSearch: true,
      valueEnum: BPMStatusEnum
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (item, record) => (
        <>
          {(tabIndex === '1' && record.approvalStatus === 0) && <>
            <a onClick={() => updateAward(record)}>分配</a>
            <Divider type="vertical"/>
            <Popconfirm title={`是否确认发起?`} placement="topRight" onConfirm={() => sendAwardBpm(record.id)} okText="是" cancelText="否">
              <a>发起</a>
            </Popconfirm>
            <Divider type="vertical"/>
          </>}
          {/*{(tabIndex === '2') && <a onClick={() => details(record)}>详情</a>}*/}
          <a onClick={() => detailsAward(record)}>详情</a>
          {(record.approvalStatus !== 0 && record.bpmUrl) && <><Divider type="vertical"/><a onClick={() => window.open(record.bpmUrl)}>审批详情</a></>}
        </>
      ),
    }
  ];


  return (
    <PageHeaderWrapper>
      <Tabs animated={false} defaultActiveKey="1" onChange={handleChangTabIndex}>
        <TabPane tab="待办理" key="1">
          <ProTable
            actionRef={actionRef}
            rowKey="id"
            request={(params) => queryAwardList(params, tabIndex)}
            columns={columns}
            toolBarRender={(action, {selectedRows}) => [
              <Button key={0} type="primary" onClick={() => addAward(null)}>新建</Button>,
            ]}
          />
        </TabPane>
        <TabPane tab="已办理" key="2">
          <ProTable
            actionRef={actionRef2}
            rowKey="id"
            request={(params) => queryAwardList(params, tabIndex)}
            columns={columns}
          />
        </TabPane>
        <CreateForm
          loading={loading}
          visible={visible}
          reanpu={reanpu}
          record={record}
          show={show}
          onCancel={handleCancel}
          onSubmit={handleSubmit}
        />
      </Tabs>
    </PageHeaderWrapper>
  )
}

export default connect(({}) => ({}))(TableList)
